package com.event.controller;
import com.alibaba.fastjson.JSON;
import com.event.pojo.Post;
import com.event.pojo.User;
import com.event.service.PostService;
import com.event.service.UserService;
import com.event.util.GetIp;
import com.event.util.SenInfoCheckUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * <p>
 * 帖子 前端控制器
 * </p>
 *
 * @author 孤雏
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/post")
@CrossOrigin(origins = "*",maxAge = 3600)
@Api(value = "用户帖子接口",tags = "用户帖子接口")
public class PostController {

    @Autowired
    PostService postService;
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/selectPost")
    @ApiOperation(value = "按时间获取帖子接口,如果传入为空则为查询全部帖子",notes = "传值进来")
    public JSON selectPost(Post post){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        List<Post> posts = postService.selectPost(post);
        try {
            for (Post post1 : posts) {
                User user = new User();
                user.setUserid(post1.getUserId());
                List<User> users = userService.selectUser(user);
                post1.setRealname(users.get(0).getRealname());
                post1.setOpenname(users.get(0).getOpenname());
                post1.setAvatar(users.get(0).getAvatar());
            }
            map.put("code",0);
            map.put("msg","200");
            map.put("count",posts.size());
            map.put("data",posts);
        } catch (Exception e) {
            map.put("code",0);
            map.put("msg","500");
            map.put("count",0);
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @GetMapping("/selectPostByView")
    @ApiOperation(value = "按浏览量获取帖子接口,如果传入为空则为查询全部帖子",notes = "传值进来")
    public JSON selectPostByView(Post post){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        List<Post> posts = postService.selectPostByView(post,"评论数");
        try {
            for (Post post1 : posts) {
                User user = new User();
                user.setUserid(post1.getUserId());
                List<User> users = userService.selectUser(user);
                post1.setRealname(users.get(0).getRealname());
                post1.setOpenname(users.get(0).getOpenname());
                post1.setAvatar(users.get(0).getAvatar());
            }
            map.put("code",0);
            map.put("msg","200");
            map.put("count",posts.size());
            map.put("data",posts);
        } catch (Exception e) {
            map.put("code",0);
            map.put("msg","500");
            map.put("count",0);
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @GetMapping("/selectPostByUptime")
    @ApiOperation(value = "按帖子更新时间获取帖子接口,如果传入为空则为查询全部帖子",notes = "传值进来")
    public JSON selectPostByUptime(Post post){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        List<Post> posts = postService.selectPostByUptime(post,"更新时间");
        try {
            for (Post post1 : posts) {
                User user = new User();
                user.setUserid(post1.getUserId());
                List<User> users = userService.selectUser(user);
                post1.setRealname(users.get(0).getRealname());
                post1.setOpenname(users.get(0).getOpenname());
                post1.setAvatar(users.get(0).getAvatar());
            }
            map.put("code",0);
            map.put("msg","200");
            map.put("count",posts.size());
            map.put("data",posts);
        } catch (Exception e) {
            map.put("code",0);
            map.put("msg","500");
            map.put("count",0);
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @GetMapping("/selectPostByPostTitle")
    @ApiOperation(value = "获取帖子接口,如果传入为空则为查询全部",notes = "传值进来")
    public JSON selectPostByPostTitle(String postTitle){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        List<Post> posts = postService.selectPostByPostTitle(postTitle,"标题");
        try {
            for (Post post1 : posts) {
                User user = new User();
                user.setUserid(post1.getUserId());
                List<User> users = userService.selectUser(user);
                post1.setRealname(users.get(0).getRealname());
                post1.setOpenname(users.get(0).getOpenname());
                post1.setAvatar(users.get(0).getAvatar());
            }
            map.put("code",0);
            map.put("msg","200");
            map.put("count",posts.size());
            map.put("data",posts);
        } catch (Exception e) {
            map.put("code",0);
            map.put("msg","500");
            map.put("count",0);
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/deletePost")
    @CacheEvict(value = "PostComment", allEntries=true)
    @ApiOperation(value = "根据id删除帖子",notes = "传值进来")
    public JSON deletePost(Long postId){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        boolean b = postService.deletePost(postId);
        String msg;
        if(b) msg="200";
        else msg="500";
        map.put("code",0);
        map.put("msg",msg);
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/insertPost")
    @ApiOperation(value = "添加帖子接口",notes = "传值进来")
    public JSON insertPost(Post post,HttpServletRequest request) throws Exception {
        GetIp getIp = new GetIp(request);
        post.setPostIp(getIp.getIpAddress());
        post.setPostViews((long)0);
        post.setPostCommentNum((long)0);
        Map<Object, Object> map = new ConcurrentHashMap<>();
        String msg;
        int i = 0;
        if (SenInfoCheckUtil.cotentFilter(post.getPostTitle())&&SenInfoCheckUtil.cotentFilter(post.getPostContent()))
            i = postService.insertPost(post);
        else {
            map.put("msg","文本敏感");
            map.put("code",4444);
            JSON json = (JSON) JSON.toJSON(map);
            return json;
        }

        if(i>0) msg="200";
        else msg="500";
        map.put("code",0);
        map.put("msg",msg);
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/viewPost")
    @ApiOperation(value = "访问帖子接口,使用后访问量+1",notes = "传值进来")
    public JSON viewPost(Post post){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        String msg;
        List<Post> posts = postService.selectPost(post);
        Post post1 = posts.get(0);
        post1.setPostViews(post1.getPostViews()+1);
        int i = postService.updatePost(post1);
        if(i>0) msg="200";
        else msg="500";
        map.put("code",0);
        map.put("msg",msg);
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/collectionPost")
    @ApiOperation(value = "收藏帖子接口,传入postId和userId",notes = "传值进来")
    public JSON collectionPost(Long postId,Long userId){
        Post post = new Post();
        post.setPostId(postId);
        List<Post> posts = postService.selectPost(post);
        Post post1 = posts.get(0);
        Map<Object, Object> map = new ConcurrentHashMap<>();
        Set<Long> list = new ConcurrentSkipListSet<>();
        list.add(postId);
        map.put("code",0);
        try {
            if (redisTemplate.opsForHash().get("collectionPost", userId.toString())==null){
                redisTemplate.opsForHash().put("collectionPost",userId.toString(),list);
            }else {
                Set<Long> collectionPost = (Set<Long>) redisTemplate.opsForHash().get("collectionPost", userId.toString());
                System.out.println(collectionPost);
                collectionPost.add(postId);
                redisTemplate.opsForHash().put("collectionPost",userId.toString(),collectionPost);
            }
            post1.setPostCollectNum(post1.getPostCollectNum()+1);
            postService.updatePost(post1);
            map.put("msg","200");
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }

        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/removeCollectionPost")
    @ApiOperation(value = "取消收藏帖子接口,只需要传帖子id",notes = "传值进来")
    public JSON removeCollectionPost(Long postId,Long userId){
        Post post = new Post();
        post.setPostId(postId);
        List<Post> posts = postService.selectPost(post);
        Post post1 = posts.get(0);
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put("code",0);
        try {
                Set<Long> collectionPost = (Set<Long>) redisTemplate.opsForHash().get("collectionPost", userId.toString());
                collectionPost.remove(postId);
                redisTemplate.opsForHash().put("collectionPost",userId.toString(),collectionPost);
                 post1.setPostCollectNum(post1.getPostCollectNum()-1);
            postService.updatePost(post1);
            map.put("msg","200");
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }

        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @GetMapping("/selectCollectionPost")
    @ApiOperation(value = "查询用户所有收藏的帖子",notes = "传值进来")
    public JSON selectCollectionPost(Long userId){
        Map<Object, Object> map = new ConcurrentHashMap<>();

        map.put("code",0);
        try {
            Set<Long> postId = (Set<Long>) redisTemplate.opsForHash().get("collectionPost", userId.toString());
            map.put("msg","200");
            map.put("count",postId.size());
            map.put("data",postId.toString());
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }

    @GetMapping("/selectCollectionSpecificPost")
    @ApiOperation(value = "查询用户是否收藏某一个帖子,传入postId和userId,返回1则用户收藏了该帖子,反之0",notes = "传值进来")
    public JSON selectCollectionSpecificPost(Long postId,Long userId){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put("code",0);
        try {
            Set<Long> allPostId = (Set<Long>) redisTemplate.opsForHash().get("collectionPost", userId.toString());
            //如果没有点赞过人则allPostId.size为空指针,return 0
            if(null==allPostId){
                map.put("result","0");
                return (JSON) JSON.toJSON(map);
            }else{
                map.put("msg","200");
                //遍历查看是否存在相同的收藏贴
                for(Long temp:allPostId){
                    if(Objects.equals(temp, postId)){
                        map.put("result","1");
                        return (JSON) JSON.toJSON(map);
                    }
                }
                //遍历完则证明不存在相同的帖子,return 0
                map.put("result","0");
            }
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }
        return (JSON) JSON.toJSON(map);
    }


    @PostMapping("/likePost")
    @ApiOperation(value = "帖子点赞接口,传postId和userId",notes = "传值进来")
    public JSON likePost(Long postId,Long userId){
        Post post = new Post();
        post.setPostId(postId);
        List<Post> posts = postService.selectPost(post);
        Post post1 = posts.get(0);
        Map<Object, Object> map = new ConcurrentHashMap<>();
        Set<Long> list = new ConcurrentSkipListSet<>();
        list.add(postId);
        map.put("code",0);
        try {
            if (redisTemplate.opsForHash().get("likePost", userId.toString())==null){
                redisTemplate.opsForHash().put("likePost",userId.toString(),list);
            }else {
                Set<Long> likePost = (Set<Long>) redisTemplate.opsForHash().get("likePost", userId.toString());
                System.out.println(likePost);
                likePost.add(postId);
                redisTemplate.opsForHash().put("likePost",userId.toString(),likePost);
            }
            post1.setPostLikeNum(post1.getPostLikeNum()+1);
            postService.updatePost(post1);
            map.put("msg","200");
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }

        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @PostMapping("/removeLikePost")
    @ApiOperation(value = "取消点赞帖子接口,传postId和userId",notes = "传值进来")
    public JSON removeLikePost(Long postId,Long userId){
        Post post = new Post();
        post.setPostId(postId);
        List<Post> posts = postService.selectPost(post);
        Post post1 = posts.get(0);
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put("code",0);
        try {
                Set<Long> likePost = (Set<Long>) redisTemplate.opsForHash().get("likePost", userId.toString());
                likePost.remove(postId);
                redisTemplate.opsForHash().put("likePost",userId.toString(),likePost);
            post1.setPostLikeNum(post1.getPostLikeNum()-1);
            postService.updatePost(post1);
            map.put("msg","200");
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }

        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
    @GetMapping("/selectLikePost")
    @ApiOperation(value = "查询用户是否点赞某一条帖子,传postId和userId,返回1则用户点赞了该帖子,反之0",notes = "传值进来")
    public JSON selectLikePost(Long postId,Long userId){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put("code",0);
        try {
            //获取该用户所有点赞的postId
            Set<Long> allPostId = (Set<Long>) redisTemplate.opsForHash().get("likePost", userId.toString());

            map.put("msg","200");
            //如果没有点赞过人则allPostId.size为空指针
            if(allPostId==null){
                map.put("result","0");
                return (JSON) JSON.toJSON(map);
            }else{
                //在allPostId中寻找postId
                for(Long temp:allPostId){
                    if(Objects.equals(temp, postId)){
                        map.put("result","1");
                        return (JSON) JSON.toJSON(map);
                    }
                }
                //遍历之后没有找到return 0
                map.put("result","0");
            }
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }
        return (JSON) JSON.toJSON(map);
    }

    @GetMapping("/selectAllLikesPost")
    @ApiOperation(value = "查询用户所有点赞帖子接口,传入userId",notes = "用户没有点赞过则返回0")
    public JSON selectAllLikesPost(Long userId){
        Map<Object, Object> map = new ConcurrentHashMap<>();
        map.put("code",0);
        try {
            Set<Long> allPostId = (Set<Long>) redisTemplate.opsForHash().get("likePost", userId.toString());
            map.put("msg","200");
            //如果没有点赞过人则allPostId.size为空指针
            if(null==allPostId){
                map.put("count","0");
                return (JSON) JSON.toJSON(map);
            }else{
                map.put("count",allPostId.size());
                map.put("data",allPostId.toString());
            }
        } catch (Exception e) {
            map.put("msg","500");
            e.printStackTrace();
        }
        JSON json = (JSON) JSON.toJSON(map);
        return json;
    }
}
